using System;
using Sedna.API.Security;

namespace Sedna.Utility.Command.API
{
    /// <summary>
    /// Abstract commands which use API calls.
    /// </summary>
    public abstract class APICommand: AbstractCommand
    {
        #region Fields

        private IUserContext userContext;

        #endregion

        #region Properties

        public IUserContext UserContext
        {
            set { userContext = value; }
        }

        protected IToken APIUserSessionKey
        {
            get { return userContext.CurrentSessionKey; }
        }

        #endregion

        #region Run

        public override CommandResult Run(string[] parameters)
        {
            try
            {
                userContext.Login();
                return DoRun(parameters);
            }
            catch (Exception e)
            {
                log.Error("Error during command execution", e);
                throw;
            }
            finally
            {
                userContext.Logout();
            }
        }

        protected abstract CommandResult DoRun(string[] parameters);

        #endregion
    }
}
